# -*- coding: utf-8 -*-
# Author: allen
# Copyright (c) 2021 RuiCare All rights reserved.
import base64
import json

from Crypto.Cipher import AES


class AesCryptor():
    def __init__(self, key=None):
        self.key = '' if key else 'BSAXnRMDlKnyFu1Q'

    def padding_to_16(self, value):
        while len(value) % 16 != 0: value += '\0'
        return str.encode(value, encoding='UTF-8')

    def encrypt(self, content):
        if isinstance(content, dict): content = json.dumps(content)
        aes = AES.new(self.padding_to_16(self.key), AES.MODE_ECB)
        encrypt_aes = aes.encrypt(self.padding_to_16(content))
        en_val = str(base64.encodebytes(encrypt_aes), encoding='UTF-8').replace(' ', '').replace('\n', '')
        return en_val

    def decrypt(self, passed_content):
        aes = AES.new(self.padding_to_16(self.key), AES.MODE_ECB)
        base64_decrypted = base64.decodebytes(passed_content.encode(encoding='UTF-8'))
        de_val = str(aes.decrypt(base64_decrypted), encoding='UTF-8').replace('\0', '')
        if de_val.startswith('{') and de_val.endswith('}') and de_val.__contains__('"'): de_val = json.loads(de_val)
        return de_val
